import { add } from '@/services/chdstore';
import { ShoppingCartOutlined } from '@ant-design/icons';
import type {
  EditableFormInstance,
  ProColumns,
} from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import SearchSelect from './SearchSelect';

type DataSourceType = {
  id: number;
  pic?: string;
  goodsName?: string;
  num?: number;
};

const defaultData: any = [];

const ShoppingList = (props, ref) => {
  const { init, setLoading } = props;
  const [form] = Form.useForm();
  const [dataSource, setDataSource] =
    useState<readonly DataSourceType[]>(defaultData);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );

  const editableFormRef = useRef<EditableFormInstance>();

  // 一键添加
  const onCheckout = () => {
    return new Promise((res) => {
      form
        .validateFields()
        .then(() => {
          const list = editableFormRef.current?.getRowsData?.() || [];
          const arr: string[] = [];
          list.forEach((item) => {
            new Array(item.num).fill(0).forEach(() => {
              arr.push(item.code);
            });
          });
          setLoading(true);
          return Promise.all(arr.map((code) => add(code)))
            .then(() => {
              res(true);
            })
            .catch(() => {
              message.error('添加有误，请清空下方购物车后重新操作');
            })
            .finally(() => {
              init();
            });
        })
        .catch(() => {
          message.error('请填写完整后再进行操作');
        });
    });
  };

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '道具名称',
      valueType: 'select',
      dataIndex: 'code',
      width: 500,
      renderFormItem: (_, { record }) => {
        return (
          <SearchSelect
            recordKey={record?.id}
            dataSource={dataSource}
            setDataSource={setDataSource}
          />
        );
      },
    },
    {
      title: '数量',
      valueType: 'digit',
      dataIndex: 'num',
      width: 150,
      formItemProps: {
        rules: [
          {
            type: 'number',
            min: 1,
            required: true,
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
    },
  ];

  useImperativeHandle(ref, () => {
    return {
      onCheckout,
    };
  });

  return (
    <>
      <EditableProTable<DataSourceType>
        editableFormRef={editableFormRef}
        rowKey="id"
        recordCreatorProps={{
          newRecordType: 'dataSource',
          position: 'bottom',
          record: () => ({ id: Date.now() }),
          creatorButtonText: '新增道具',
        }}
        columns={columns}
        value={dataSource}
        onChange={setDataSource}
        toolBarRender={() => {
          return [
            <Button
              key="save"
              icon={<ShoppingCartOutlined />}
              onClick={onCheckout}
            >
              一键添加
            </Button>,
          ];
        }}
        editable={{
          form,
          type: 'multiple',
          editableKeys,
          actionRender: (row, config) => [
            <a
              key="delete"
              onClick={() => {
                config?.onDelete?.(row.id, row);
              }}
            >
              删除
            </a>,
          ],
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          onChange: setEditableRowKeys,
        }}
      />
    </>
  );
};

export default forwardRef(ShoppingList);
